package com.jiepos.mpos.biz.appInfM.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.biz.affix.service.AppAffixInfService;
import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.HeadAdvDao;
import com.jiepos.mpos.common.entity.App_Client_HeadadvEntity;
import com.jiepos.mpos.common.entity.App_Ins_AppEntity;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.common.entity.GpsEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;


/**
 *
 *
 * <p>标题: —— 广告位维护表类</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @ProjectName:  [mpos]
 * @Package com.jiepos.mpos.biz.appInfM.service
 * @author 余翼膑
 * @version 1.0
 * @since 2017年9月25号
 * @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class HeadAdvService extends BaseService {

    @Autowired
    private HeadAdvDao headAdvDao;
    @Autowired
    private AppAffixInfService appAffixInfService;

    /**
     * 查询通道信息列表json分页数据
     * @param pagination
     * @param appClientEntity
     * @return
     */
    public Map getAppHeadAdv(HttpServletRequest request, Pagination pagination, App_Client_HeadadvEntity appClientEntity, App_Ins_AppEntity appInsAppEntity, App_Ins_InfEntity appInsInfEntity){
        StringBuffer sb = getInitSql("t1").append(",");
        sb.append("t1.ins_uuid,t1.adv_uuid as uuid,t1.adv_title,t1.adv_type,t1.adv_no,t1.adv_place||'-'||t4.code_desc as advPlace,t1.headpic_path,t1.event_path,t3.app_name_app,");
        sb.append(" t2.ins_cd || '-' || t2.ins_cn_nm ins_cn_nm  FROM ");
        sb.append(DBConstant.Table.T_APP_CLIENT_HEADADV);
        sb.append(" t1 LEFT JOIN ");
        sb.append(DBConstant.Table.T_APP_INS_INF).append(" t2 ON t1.ins_uuid = t2.ins_uuid");
        sb.append(" LEFT JOIN ");
        sb.append(DBConstant.Table.T_APP_INS_APP).append(" t3 ON t1.ins_uuid = t3.ins_uuid");
        sb.append(" LEFT JOIN ");
        sb.append(DBConstant.Table.T_APP_CODE_LIST).append(" t4 ON t1.adv_place = t4.code_val and t4.code_tp='ADV_PLACE' ");
        sb.append(" where 1=1 ");
        List list = new ArrayList();
        if (!StringUtils.isBlank(appInsAppEntity.getApp_name_app())) {
            sb.append( " and t3.app_name_app like ? " );
            list.add("%" + appInsAppEntity.getApp_name_app() + "%");
        }
        if (!StringUtils.isBlank(appClientEntity.getAdv_place())) {
            sb.append( " and t1.adv_place like ? " );
            list.add("%" + appClientEntity.getAdv_place() + "%");
        }
        //机构号
        if (!StringUtils.isBlank(appInsInfEntity.getIns_cd())) {
            sb.append( " and t2.ins_cd like ? " );
            list.add("%" + appInsInfEntity.getIns_cd() + "%");
        }
        //机构名称
        if (!StringUtils.isBlank(appInsInfEntity.getIns_cn_nm())) {
            sb.append( " and t2.ins_cn_nm like ? " );
            list.add("%" + appInsInfEntity.getIns_cn_nm() + "%");
        }
        pagination.queryString = sb.toString();
        pagination = getInsAuthSql(request, pagination, "t1", null);
        pagination = this.getOrderSql(pagination, "t1");
        return headAdvDao.getPaginationMap(pagination,"t1",list);
    }

    /**
     * 根据记录id查询实体对象
     * @param   adv_uuid
     * @return
     */
    public Map gettHeadAdvfById(String adv_uuid) {
        if (StringUtils.isBlank(adv_uuid) || adv_uuid.equals("undefined")) {
            return new HashMap();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("select t1.ins_uuid,t1.adv_uuid,t1.adv_title,t1.adv_no,t1.adv_place,t1.event_path,t1.headpic_path,t1.adv_type,t1.rec_id,");
        sb.append("t2.ins_cd || '-' || t2.ins_cn_nm inst_name");
        sb.append( " from ");
        sb.append(DBConstant.Table.T_APP_CLIENT_HEADADV);
        sb.append(" t1 left join ").append(DBConstant.Table.T_APP_INS_INF).append(" t2 on t1.ins_uuid= t2.ins_uuid");
        sb.append(" where  t1.adv_uuid = ? ");
        List<String> list = new ArrayList<>();
        list.add(adv_uuid);
        List<Map<String, Object>> results = headAdvDao.queryForList(getOrderSql(sb.toString(), "t1"), list);
        Map returnMap = results != null ? results.get(0) : new HashMap<String, Object>();
        return this.getHeadAdvPath(returnMap,adv_uuid);
    }

    /**
     * 获取广告位图片地址信息
     *
     * @param adv_uuid
     * @return
     */
    public Map getHeadAdvPath(Map headAdvMap,String adv_uuid) {
        StringBuffer sbBuf = new StringBuffer();
        sbBuf.append("select t1.affix_uuid, t1.affix_tp,t1.store_tp,t1.affix_path,t1.affix_water_path from "+ DBConstant.Table.T_APP_AFFIX_INF +" t1 ");
        sbBuf.append("where t1.affix_tp = '" + SystemConstant.AFFIX_TP_04 + "' and t1.affix_idx = ? ");
        sbBuf.append("order by t1.store_tp asc");
        List list = new ArrayList();
        list.add(adv_uuid);
        List<Map<String, Object>> list1 = headAdvDao.queryForList(sbBuf.toString(), list);
        Map advMap = new HashMap();
        for(int i = 0; i < list1.size(); i++){
            advMap = list1.get(i);
            String store_tp = String.valueOf(advMap.get("store_tp"));
            String affix_path = String.valueOf(advMap.get("affix_path"));
            String affix_uuid = String.valueOf(advMap.get("affix_uuid"));
            headAdvMap.put("affix_path"+store_tp,affix_path);
            headAdvMap.put("affix_uuid",affix_uuid);
        }
        return headAdvMap;
    }

    /**
     * 保存机构
     * @param  appClientEntity
     * @param map
     */
    public void saveHeadAdv(HttpServletRequest request,App_Client_HeadadvEntity appClientEntity,Map map){
        //当前用户
        appClientEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
        if(org.apache.commons.lang.StringUtils.isBlank(appClientEntity.getIns_uuid())){
            appClientEntity.setIns_uuid(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_INS_UUID)));
        }
        if(!StringUtils.isBlank(appClientEntity.getAdv_uuid())){
            //广告位修改
            appClientEntity = (App_Client_HeadadvEntity) this.saveCommonData(appClientEntity ,map,"update" );
            List noChangeList = new ArrayList();
            noChangeList.add("adv_uuid");
            noChangeList.add("rec_crt_ts");
            headAdvDao.update(appClientEntity, noChangeList);
            appAffixInfService.saveAffixPic(request,appClientEntity.getAdv_uuid(),map);
        }else{
            //广告位新增
            appClientEntity.setLast_oper_in(SystemConstant.OPER_ADD);
            appClientEntity.setAdv_uuid(IDFactoryUtil.getUUID());
            App_Client_HeadadvEntity newInsAppEntity = (App_Client_HeadadvEntity) this.saveCommonData(appClientEntity, map, "null");
            headAdvDao.save(appClientEntity);
            appAffixInfService.saveAffixPic(request,appClientEntity.getAdv_uuid(),map);
        }
    }
    /**
     * 获取app初始化广告信息
     * @param gpsEntity
     * @param adv_place 广告图片位置
     * @return
     */
    public List getHeadAdvList(GpsEntity gpsEntity,String adv_place){
    	String appType = gpsEntity.getAppType();
    	StringBuilder sql = new StringBuilder();
    	sql.append("select t1.adv_uuid as \"adv_uuid\",t1.adv_title as \"adv_title\",t1.adv_no as \"adv_no\",t1.adv_type as \"adv_type\",t1.event_path as \"event_path\",t1.adv_place as \"adv_place\"  ");
    	sql.append(" from "+DBConstant.Table.T_APP_CLIENT_HEADADV+" t1 ");
    	sql.append("  where t1.ins_uuid in(select ins_uuid from "+ DBConstant.Table.T_APP_INS_APP+" t2 where 1 = 1   ");
    	if(SystemConstant.APP_TYPE_IOS.equals(appType)){
    	sql.append(" and t2.ios_appid=?");
    }else{
        sql.append(" and t2.android_appid=?");
    }
        sql.append("  ) ");
         sql.append(" and t1.rec_st="+SystemConstant.REC_ST_1);
    	List paramList = new ArrayList();
    	paramList.add(gpsEntity.getApp_id());
    	List<Map> list = headAdvDao.queryForList(sql.toString(),paramList);
    	log.debug("获取广告图片附件信息");
    	Map headAdvMap = null;
    	List picList = null;
    	Map picMap = null;
    	for(int i = 0 ; i < list.size() ; i++){
    		headAdvMap = list.get(i);
    		String adv_uuid = String.valueOf(headAdvMap.get("adv_uuid"));
    		picList = appAffixInfService.getAffixPic(SystemConstant.AFFIX_TP_04, adv_uuid);
    	 
    		for(int j = 0 ; j < picList.size() ; j++){
    			picMap = (Map)picList.get(j);
    			String store_tp = String.valueOf(picMap.get("store_tp"));
    			String affix_path = String.valueOf(picMap.get("affix_path"));
    			if(SystemConstant.STORE_TP_04_01.equals(store_tp)){
    				headAdvMap.put("android_pic", affix_path);
    			}
    			if(SystemConstant.STORE_TP_04_02.equals(store_tp)){
    				headAdvMap.put("ios_2xpic", affix_path);
    			}
    			if(SystemConstant.STORE_TP_04_03.equals(store_tp)){
    				headAdvMap.put("ios_3xpic", affix_path);
    			}    			
    		}
   
    	}
    
    	return list;   	
    }

    /**
     * 删除方法
     * @param adv_uuids 主键唯一标识
     */
    public void deleteHeadAdvByIds(String adv_uuids) {
        headAdvDao.deleteByStatus("adv_uuid",adv_uuids);
    }
}
